import { onWindowMessage } from '@/apps/content_script/cs_postmessage'

const clone = (data: any) => {
    const str = JSON.stringify(data)
    if (str === undefined) return undefined
    return JSON.parse(str)
}

onWindowMessage(window, ({ cmd, args }: any) => {
    switch (cmd) {
        case 'INJECT_READY': {
            document.body.setAttribute('data-injected', 'done')
            return true
        }

        case 'INJECT_RUN_EVAL': {
            // Note: clone the data in case it contains some Object that can't be passed via postMessage (eg. HTMLDocument)
            // eslint-disable-next-line no-eval
            return Promise.resolve(window.eval(args.code))
                .then(result => {
                    return { result: clone(result) }
                })
        }
    }
})

/**
 * 跑在MAIN环境
 */
